<script setup>
import { message } from 'ant-design-vue'
import * as monaco from "monaco-editor";
import cdcPropertiesApi from "@/api/cdc/cdcPropertiesApi.js";

const compFileEditor = ref();
const props = defineProps(["cdcId"])

let monacoEditor = null;



onMounted(async () => {
	const data = await queryPropertiesByCdcId();

	let str = buildProperties(data);
	init(str);
})

const queryPropertiesByCdcId = async () => {
	const data = await cdcPropertiesApi.queryByCdcId({
		cdcId: props.cdcId
	});
	return data;
}
const buildProperties = (data) => {

	if (!data) {
		return
	}
	let str = "";
	for (let d of data) {
		str += d.configKey + " = " + d.configValue + "\n";
	}
	return str;
}

const init = (str) => {
	// 使用 - 创建 monacoEditor 对象
	if (monacoEditor) {
		clear();
		return;
	}
	nextTick(() => {
		monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
			validate: false
		});
		monacoEditor = monaco.editor.create(compFileEditor.value, {
			theme: "vs-dark", // 主题
			value: str, // 默认显示的值
			language: "log",
			folding: true, // 是否折叠
			foldingHighlight: true, // 折叠等高线
			foldingStrategy: "indentation", // 折叠方式  auto | indentation
			showFoldingControls: "always", // 是否一直显示折叠 always | mouseover
			disableLayerHinting: true, // 等宽优化
			emptySelectionClipboard: false, // 空选择剪切板
			selectionClipboard: false, // 选择剪切板
			automaticLayout: true, // 自动布局
			codeLens: false, // 代码镜头
			scrollBeyondLastLine: false, // 滚动完最后一行后再滚动一屏幕
			colorDecorators: true, // 颜色装饰器
			accessibilitySupport: "off", // 辅助功能支持  "auto" | "off" | "on"
			lineNumbers: "on", // 行号 取值： "on" | "off" | "relative" | "interval" | function
			lineNumbersMinChars: 5, // 行号最小字符   number
			enableSplitViewResizing: false,
			readOnly: false, //是否只读  取值 true | false
		});

	})

}

const save = async () => {
	const properties = valueToProperties();
	await cdcPropertiesApi.save({
		cdcId: props.cdcId,
		properties: properties
	});


}
const valueToProperties = () => {
	const value = monacoEditor.getValue();
	if (!value) {
		return
	}
	const lines = value.split('\n');
	const properties = [];

	lines.forEach(line => {
		const [key, value] = line.split('=');
		if (key && value) {
			properties.push({
				configKey: key.trim(),
				configValue: value.trim()
			})
		}
	});

	return properties;
}

defineExpose({
	save
})



</script>

<template>


	<a-row :gutter="10" class="mb-2">
		<a-col :span="24">
			<a-card>
				<div style="position:flexd;height:560px;">
					<div ref="compFileEditor" style="height: 100%; text-align: left"></div>
				</div>
			</a-card>
		</a-col>

	</a-row>
</template>


<style lang="less"></style>
